<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\severs\BarcodeSever;
use app\home\severs\InReceiptSever;
use app\home\severs\OutReceiptSever;
use app\home\severs\PrintSevers;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class MaterialDossier
 * @package app\home\controller
 * 物料档案
 */
class MaterialDossier extends BaseController
{
protected $table='material_dossier';
protected $title='物料档案';
private $sessionKey='page_MaterialDossier';
    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->param;
            if (request()->isAjax()) {

                $where[]=['status','>',-1];
                foreach (['status','warehouse_id'] as $v){
                    if (isset($this->param[$v])&&$this->param[$v]){
                        $where[]=[$v,'=',$this->param[$v]];
                    }
                }
                if (isset($param['type']) &&$param['type']){
                    $types=$this->getAllSubIds($param['type']);
                    $types[]=$param['type'];
                    $where[]=['type','in',$types];
                }
                foreach (['bar_code','name','brand','specs','buyCode','taxCode'] as $v){
                    if (isset($this->param[$v])&&$this->param[$v]){
                        $where[]=[$v,'like','%'.$this->param[$v].'%'];
                    }
                }
                if (isset($param['create_time']) &&$param['create_time']){
                    $times=explode('~',$param['create_time']);
                    $b_time=strtotime($times[0]);
                    $e_time=strtotime($times[1].' 23:59:59');
                    $where[]=['create_time','between',[$b_time,$e_time]];
                }
                $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
//                $rows=5000;
                $list = Db::name($this->table)
                    ->where($where)
                    ->field("*,(select name from fy_material_type mt where mt.id=type)typeName,
                    (select name from fy_warehouse w where w.id= warehouse_id) mdName")
                    ->paginate($rows);
                session($this->sessionKey,$where);
                return table_assign(0, '', $list);
            } else {
                $wList=Db::name('warehouse')->where('status',1)->field('id,name')->select();
                View::assign('wList',$wList);
                return view();
            }

    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            Db::StartTrans();
            try {
                $param=$this->param;
//           if (!$param['warehouse_detail_id']||!$param['warehouse_id']){
//               return to_assign(1,'请选择仓库');
//           }
                $brand=$param['brand'];
                $brand1=$param['brand1']??'';
                unset($param['brand1']);
                if ($brand1=='无'){
                    if ($brand==''){
                        $param['brand']='无';
                    }
                }else{
                    $param['brand']=$brand1;
                }
                if (!$param['warehouse_id']){
                    throw new Exception('请选择仓库');
                }
                unset($param['file']);
                $whereSpecs[]=['status','>',-1];
                $whereSpecs[]=['specs','=',$param['specs']];

                $param['update_time']=time();
                $whereAdd[]=['status','>',-1];
                $whereAdd[]=['bar_code','=',$param['bar_code']];
                if (isset($param['id'])&&$param['id']){
                    $whereAdd[]=['id','<>',$param['id']];
                    $whereSpecs[]=['id','<>',$param['id']];
                }

                $hasSpecs=Db::name($this->table)->where($whereSpecs)->count('id');
                if ($hasSpecs){
                    throw new Exception('型号重复');
                }
                $has=Db::name($this->table)->where($whereAdd)->count('id');
                if ($has){
                    throw new Exception('编码重复');
                }
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);
                } else {
                    $param['create_time'] = time();
                    $rid = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    $param['mdId']=$rid;
                    $param['orderNum']=dJBHBySql('in_receipt','orderNum','');
                    $inRes=InReceiptSever::create($param,$this->uid);
                    if ($inRes['code']==1){
                        throw new Exception($inRes['msg']);
                    }
                    add_log('add', $rid, $param,$this->title);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail=[];
            if ($id > 0) {
                $detail = \app\home\model\MaterialDossier::where('id', $id)->with(['cangwei'])->find();
            }else{
                $detail['type']=$param['type_id']??0;
                $detail['bar_code']=dJBHBySql($this->table,'bar_code','',false,'100000');
            }
            View::assign('detail', $detail);
            $typeList=Db::name('material_type')->where('status',1)->field('id,pid,name as title')->select();
            $typeList=set_recursion($typeList);
            $warehouse=Db::name('warehouse')->where('status','1')->field('id,name')->select();
            View::assign('id', $id);
            View::assign('warehouse', $warehouse);
            View::assign('typeList', $typeList);

            $pinpaiList=Db::name($this->table)->where('status','>','-1')
                ->where('brand','<>','')
                ->where('brand','<>','无')
                ->group('brand')
                ->column('brand');
            View::assign('pinpaiList', $pinpaiList);
            return view('form');
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/4/1
     * 启用/禁用
     */
    public function doCheck()
    {
        $param = get_params();
        $param['update_time']=time();
        $res = Db::name($this->table)->strict(false)->field('id,status,update_time')->update($param);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                $kyy=[
                    '销售',
                    '采购',
                    '生产'
                ];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {
                    $bar_code=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    if ($bar_code){
                    $name=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $brand=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $type=(int)$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $specs=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                    $unit=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $buyCode=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                    $taxCode=$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getFormattedValue();
                    $proPrice=(float)$objPHPExcel->getActiveSheet()->getCell("I" . $j)->getFormattedValue();
                    $stock_min=(int)$objPHPExcel->getActiveSheet()->getCell("J" . $j)->getFormattedValue();
                    $stock_max=(int)$objPHPExcel->getActiveSheet()->getCell("K" . $j)->getFormattedValue();
                    $warehouse_id=(int)$objPHPExcel->getActiveSheet()->getCell("L" . $j)->getFormattedValue();
                    $warehouse_detail_id=(int)$objPHPExcel->getActiveSheet()->getCell("M" . $j)->getFormattedValue();
                    $remark=$objPHPExcel->getActiveSheet()->getCell("N" . $j)->getFormattedValue();

                    if (!$type||!Db::name('material_type')->where('id',$type)->where('status','1')->value('id')){
                        $warText="第".($j-1) ."行类型填写有误:type:".$type;
                        throw new Exception($warText);
                    }
                    if ($stock_min&&$stock_max){
                        if ($stock_min<0||$stock_max<0||$stock_max<$stock_min){
                            $warText="第".($j-1)."行库存上下限填写有误";
                            throw new Exception($warText);
                        }
                    }
                    if (!$bar_code||!$name||!$specs||!$unit||!$brand||!$type){
                        $warText="第".($j-1)."行内容填写有误";
                        throw new Exception($warText);
                    }
                        $have_bar_code=Db::name($this->table)->where('bar_code','=',$bar_code)->where('status','>',-1)->count();
                    if ($have_bar_code){
                        $warText="第".($j-1)."行编码已存在";
                        throw new Exception($warText);
                    }
                    $haveSpecs=Db::name($this->table)->where('specs','=',$specs)->where('status','>',-1)->count();
                        if ($haveSpecs){
                            $warText="第".($j-1)."行型号已存在";
                            throw new Exception($warText);
                        }
                    if ($warehouse_id&&!Db::name('warehouse')->where('id',$warehouse_id)->where('status','1')->value('id')){
                        $warText="第".($j-1) ."行仓库填写有误";
                        throw new Exception($warText);
                    }
                    if ($warehouse_detail_id&&!Db::name('warehouse_detail')->where('id',$warehouse_detail_id)->where('warehouse_id',$warehouse_id)->where('status','1')->value('id')){
                        $warText="第".($j-1) ."行仓位填写有误";
                        throw new Exception($warText);
                    }
                    $importData[] = [
                        "name" => $name,
                        "brand" => $brand,
                        "type" => $type,
                        "specs" => $specs,
                        "unit" => $unit,
                        "proPrice" => $proPrice,
                        "taxCode" => $taxCode,
                        "buyCode" => $buyCode,
                        "useType" => '',
                        "stock_type" => '',
                        "stock_min" => $stock_min,
                        "stock_max" => $stock_max,
                        "bar_code" => $bar_code,
                        "warehouse_id" => $warehouse_id?$warehouse_id:1,
                        "warehouse_detail_id" => $warehouse_detail_id?$warehouse_detail_id:1,
                        'remark'=>$remark??'',
                        "deleted" =>0,
                        "create_time"=>time(),
                        'update_time'=>time()
                    ] ;
                }
                }

                if ($importData){
                    $wlData=[];
                    foreach ($importData as $v){
                        $id=Db::name($this->table)->insertGetId($v);
                        $wlData[]=[
                            'mdId'=>$id,
                            'warehouse_id'=>$v['warehouse_id']
                        ];
                    }
                    $param=[
                        'orderNum'=>$this->getDJBHBuySql('in_receipt','orderNum',''),
                        'wlData'=>$wlData
                    ];
                    $res=InReceiptSever::create($param,$this->uid);
                    if ($res['code']==1){
                        throw new Exception($res['msg']);
                    }
//                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $importData,$this->title);
                }
                Db::commit();
            }

        }catch (Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    /**
     * @return \json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * date:2024/7/8
     * 检测
     */
    public function detection()
    {
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $barCodes = [];
                $res=[];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 1; $j <= $highestRow; $j++) {
                    $bar_code=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    if ($bar_code){
                        $barCodes[]=$bar_code;
                    }
                }

                if ($barCodes){
                   $codes=Db::name($this->table)->where('deleted',0)
                       ->where('bar_code','in',$barCodes)
                       ->column('bar_code');
                   if (count($codes)!=count($barCodes)){
                       foreach ($barCodes as $key =>$v){
                           $nCode=in_array($v,$codes);
                           if (!$nCode){
                               $res[]=[
                                   'k'=>$key+1,
                                   'code'=>$v
                               ];
                           }
                       }
                   }
//                    add_log('import', '', $importData,$this->title);
                }

            }
        }catch (Exception $e){
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功',$res);
    }

    public function changeCk()
    {
        $id=$this->param['id']??'';
        if ($this->request->isPost()){
            $wId=$this->param['warehouse_id']??'';
            if (!$wId){
                return to_assign(1,'参数缺失');
            }
            $wd_id=Db::name('warehouse_detail')->where('status','1')
                ->where('warehouse_id',$wId)->order('id ASC')->limit(1)->value('id');
            if (!$id){
                return to_assign(1,'参数缺失');
            }
            $upData=[
                'warehouse_id'=>$wId,
                'warehouse_detail_id'=>$wd_id,
                'update_time'=>time()
            ];
            Db::name($this->table)->where('id','in',$id)->update($upData);
            add_log('edit', $this->param['id'], $this->param,$this->title);
            return to_assign(0,'操作成功');
        }
        $warehouse=Db::name('warehouse')->where('status','1')->field('id,name')->select();
        View::assign('id', $id);
        View::assign('warehouse', $warehouse);
        return \view();
    }

    public function printPage()
    {
        $ids = $this->param['id']??'';
        $content = '';
        $num=[];
        $list=Db::name($this->table)->where('id','in',$ids)->field('id,bar_code,name,specs')->select();
        foreach ($list as $key=> $v) {
            //材料信息
            $barcode = $v['bar_code'];

            $content .= <<<efo
                 <div class="qr-content num_{$key}">
                      <img alt="" src="/home/Api/getBarcodeImg?barcode=$barcode">
<!--                      <div class="qr-content-barcode"></div>-->
                      <div style="font-size: 24px;line-height: 30px;margin-top: 10px">
                      {$v['name']}-{$v['specs']}
                      <br>
<!--                      规格型号:-->
                      </div>
                 </div>
efo;
        }
        $html = <<<efo
<style>

.printEditPage{width: 100%;height: 500px;overflow: auto;}
.printEditPage>ul>li{float: left;margin: 5px;padding: 5px}
.qr-content{width: auto;height: auto;background-color: #F0F8FA;text-align: center;margin:0;padding:10px;;overflow: auto}
/*.qr-content img{width: 300px}*/
/*.qr-content img{max-height: 80px;width: 300px;height: auto}*/
.qr-content-barcode{font-size: 15px;font-weight: bold;margin:5px 0 0 0}
.qr-content-bottom{word-wrap:break-word;}
.qr-num{width: 250px;margin: 10px}
.page-num-simple{
display: none;
}

.qr-content{width: auto;height: 181px;margin: 0;overflow: hidden;background-color: white}
/*.qr-content img{width: 120px;}*/
.qr-content-bottom{font-size: 12px}
</style>
efo;

 $html.= <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                        <div data-op-type='mix-box'>
                             <div class="nop-fill-box">
                              {$content}
                             </div>
                        </div>
                    </div>
                  
eof;


//echo($html);
        $print = new PrintSevers();
        return $print->showPrint( $html, 'portrait', ['padding' => "0mm", 'pageSizeOption' => ['width' => '80mm', 'height' => '49mm']]);
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)
            ->where($where)
            ->field("*,(select name from fy_material_type mt where mt.id=type)typeName")
            ->select()->each(function ($item){
                $item['status']=$item['status']==1?'启用':'禁用';
                return $item;
            });
        $title = [
            'typeName' => '分类',
            'bar_code' => '编码',
            'name' => '物料名称',
            'specs' => '规格型号',
            'unit' => '单位',
            'remark' => '备注',
            'status' => '状态',
        ];
        $name = "物料档案";
        exportXlsData($name,$title,$list);
      exit();
    }
}